<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline" ref="queryForm">
          <el-form-item label="手机号">
            <el-input v-model="queryParams.telPhone" placeholder="请输入手机号码" clearable></el-input>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
                v-model="dateArr"
                type="datetimerange"
                :picker-options="pickerOptions"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit" :disabled="isLoading">查询</el-button>
            <el-button @click="handleReset()">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
          :data="tableData"
          border
          style="width: 100%" v-loading="isLoading">
        <el-table-column
            type="index"
            label="编号"
            width="180"
            align="center"
        >
        </el-table-column>
        <el-table-column
            prop="wid"
            label="逻辑编号"
            width="180"
            align="center"
        >
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="日期"
            width="180"
            align="center"
        >
        </el-table-column>
        <el-table-column
            prop="workerName"
            label="姓名"
            width="180"
            align="center"
        >
        </el-table-column>
        <el-table-column
            prop="roleName"
            label="角色名称"
            width="180"
            align="center"
        >
        </el-table-column>
        <el-table-column
            prop="account"
            label="账户"
            width="180"
            align="center"
        >
        </el-table-column>
        <el-table-column
            prop="photoThumbnail"
            label="缩略图片" v-slot="scope"
            align="center"
        >
          <el-avatar :size="27" :src="scope.row.photoThumbnail|| defaultFace"></el-avatar>
        </el-table-column>
        <el-table-column
            prop="telPhone"
            label="电话"
            align="center"
        >
        </el-table-column>
        <el-table-column
            label="状态"
            align="center"
            v-slot="scope"
        >
          <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="1"
              inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
              @change="handleChangeStatus(scope.row)"
          >
          </el-switch>
        </el-table-column>
        <el-table-column
            label="操作"
            align="center"
            v-slot="scope"
        >
          <el-button @click="handleDistributeRole(scope.row)">分配角色</el-button>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageSize"
          :page-sizes="[  10,20,30, 50]"
          :page-size="queryResult.pageNum"
          layout="total, sizes, prev, pager, next, jumper"
          :total="queryResult.totalSize"
          :disabled="isLoading"
      >
      </el-pagination>
      <worker-distribute-role ref="workerDistributeRoleDlg"></worker-distribute-role>
    </el-card>

  </div>

</template>
<script>
import {getAllWorkerList, StopOrStartWorker} from "@/api/worker/worker";
//导入子组件
import workerDistributeRole from '@/pages/worker/compontent/worker_distribute_role.vue'

export default {
  name: "WorkerIndex",
  components: {
    workerDistributeRole
  },
  data() {
    return {
      //是否加载数据 false加载成功  true正在加载
      isLoading: false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      //时间数组
      dateArr: [],
      //查询条件
      queryParams: {
        pageSize: 1,
        pageNum: 10,
        name: '',
        account: '',
        telPhone: '',
        qqWord: '',
        startTime: null,
        endTime: null
      },
      //查询结果
      queryResult: {},
      //定义头像的默认值
      defaultFace: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",

      tableData: [],

    }
  },
  watch: {
    dateArr: {
      deep: true,
      handler(newVal) {
        this.queryParams.startTime = this.formatDate(newVal[0])
        this.queryParams.endTime = this.formatDate(newVal[1])
      }
    }
  },
  created() {
    this.loadWorker()
  },
  methods: {
    //工作者分页
    loadWorker() {
      //未加载完成
      this.isLoading = true
      getAllWorkerList(this.queryParams).then(res => {
        //debugger
        console.log("工作者分页：：：", res);
        if (res.data.code === "200") {
          // console.log(res);
          //当前页,当前页显示多少条数据,展示的多少条,总页数,总记录数
          const {currPage, pageSize, rows, totalPage, totalSize} = res.data.data;
          //当前页,当前页显示多少条数据,和后端数据一致
          console.log("查询参数:", this.queryParams);
          this.queryParams.pageSize = currPage;
          this.queryParams.pageNum = pageSize;
          //展示的多少条,总页数,总记录数
          this.queryResult = {rows, totalPage, totalSize}
          //开关只能是字符串
          this.queryResult.rows.forEach(e => {
            e.status = e.status + ''
          })
          this.tableData = this.queryResult.rows
          console.log("查询参数:", this.queryParams);
          this.$message.success('工作者分页查询成功。。。')
        } else {
          this.$message.error('工作者分页查询失败。。。')
        }
      }).finally(() => {
        //加载完成
        this.isLoading = false
      })
    },
    //把Date转换成字符串 yyyy-MM-dd HH:mm:ss
    formatDate(date, format = 'yyyy-MM-dd HH:mm:ss') {
      if (!(date instanceof Date)) {
        date = new Date(date);
      }
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      const second = String(date.getSeconds()).padStart(2, '0');
      return format
          .replace('yyyy', year)
          .replace('MM', month)
          .replace('dd', day)
          .replace('HH', hour)
          .replace('mm', minute)
          .replace('ss', second);
    },
    onSubmit() {
      console.log("查询参数:::", this.queryParams);
      //查询
      this.loadWorker()
    },
    //重置
    handleReset() {
      this.$refs.queryForm.resetFields()
    },
    //每页显示多少条数据
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.queryParams.pageNum = val;
      this.queryParams.pageSize = 1;
      this.loadWorker()
    },
    //当点击不同的页号时
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.queryParams.pageSize = val;
      this.loadWorker()
    },
    //启用或者禁用(暂时不支持禁用)
    handleChangeStatus(user) {
      // debugger
      console.log("当前查询的对象：：：", user);
      const data = {
        workId: user.wid,
        manageId: ''
      }
      StopOrStartWorker(data).then(res => {
        if (res.data.code === "200") {
          // console.log(res);
          this.$message.success(res.data.message)
          this.loadWorker()
        } else {
          this.$message.error(res.data.message)
        }
      }).finally(() => {
        this.loadWorker()
      })
    },
    //分配角色
    handleDistributeRole(user) {
      //调用子组件的方法
      this.$refs.workerDistributeRoleDlg.showAndInit(user)
    }
  }
}
</script>


<style scoped>

</style>
